package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final String WX_LOGIN_ADDR = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //只能获取到授权码
        String authCode = userLoginDTO.getCode();//唯一,5分钟，一次性
        //根据授权码获取唯一标识id
        String openId = getOpenId(authCode);
        //如果授权码有问题直接抛出异常
        if (openId == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //业务分析
        //1.判断是不是第一次登录=>根据数据库查询 唯一标识id
        User user = userMapper.findUserByOpenId(openId);
        //2.第一次登录=>注册
        if (user == null) {
            user = User.builder().openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }
        //3.后续登录=>直接返回
        return user;
    }

    /**
     * 根据授权码获取用户唯一标识“openId”
     *
     * @param authCode
     * @return
     */
    private String getOpenId(String authCode) {
        try {
            HashMap<String, String> parmMap = new HashMap<>();
            //使用HttpClien发送登录请求
            //=>通过参数去微信拿OpenId
            parmMap.put("appid", weChatProperties.getAppid());      //小程序 appId
            parmMap.put("secret", weChatProperties.getSecret());    //小程序 appSecret
            parmMap.put("js_code", authCode);
            parmMap.put("grant_type", "authorization_code");

            String jsonStr = HttpClientUtil.doGet(WX_LOGIN_ADDR, parmMap);
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(jsonStr, Map.class);
            return (String) map.get("openid");
        } catch (JsonProcessingException e) {
            //throw new RuntimeException(e);
            System.err.println(e.getMessage());
        }
        return null;
    }
}
